package com.chzc.initializer;


import com.chzc.entity.DevilMessage;
import com.chzc.util.DevilMessageDecoder;
import com.chzc.util.DevilMessageEncoder;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

import java.nio.charset.StandardCharsets;


public class DevilConsumerInitializer extends ChannelInitializer<SocketChannel> {

    private SimpleChannelInboundHandler<DevilMessage> simpleChannelInboundHandler;

    public DevilConsumerInitializer(SimpleChannelInboundHandler<DevilMessage> simpleChannelInboundHandler) {
        this.simpleChannelInboundHandler = simpleChannelInboundHandler;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 加入 自定义编码器
        pipeline.addLast(new DevilMessageEncoder());
        // 自定义解码器
        pipeline.addLast(new DevilMessageDecoder());
        pipeline.addLast(simpleChannelInboundHandler);
        // 空闲检测
        pipeline.addLast(new IdleStateHandler(0, 3, 0));
        // 每秒发送心跳包
        pipeline.addLast(new ChannelDuplexHandler() {
            @Override
            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                IdleStateEvent event = (IdleStateEvent) evt;
                if (event.state() == IdleState.WRITER_IDLE) {
                    // 发送心跳数据包
                    DevilMessage devilMessage = new DevilMessage();
                    devilMessage.setLen("0".getBytes(StandardCharsets.UTF_8).length);
                    devilMessage.setContent("0".getBytes(StandardCharsets.UTF_8)); //占位符
                    devilMessage.setMessageIdLen("0".getBytes(StandardCharsets.UTF_8).length);
                    devilMessage.setMessageId("0".getBytes(StandardCharsets.UTF_8));//占位符
                    devilMessage.setQueueLen("o".getBytes(StandardCharsets.UTF_8).length);
                    devilMessage.setQueueName("o".getBytes(StandardCharsets.UTF_8)); //占位符
                    devilMessage.setStatus(1); // 生产者
                    devilMessage.setPingType(true); //消息类型为心跳
                    ctx.writeAndFlush(devilMessage);
                }
            }
        });
    }
}
